package Look;



import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * * look锁之精准通知
 *
 *  *  * 笔记：Java里面如何进行工程级别的多线程编写
 *  * 1 多线程变成模板（套路）-----上
 *  *     1.1  线程    操作    资源类
 *  *     1.2  高内聚  低耦合
 *  * 2 多线程变成模板（套路）-----下
 *  *     2.1  判断
 *  *     2.2  干活
 *  *     2.3  通知
 */

class ShareResource {

    private int number = 0;
    private Lock lock = new  ReentrantLock();  //锁
    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();   //等待，和通知
    Condition c3 = lock.newCondition();


    public void p1(){
        lock.lock();
        try {
        while(number!=0){

             c1.await();   //等待

        }

    for (int i = 0; i <5 ; i++) {

          System.out.println(Thread.currentThread().getName());

           }

        number = 1;
        c2.signal(); //只唤醒c2.await();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
             lock.unlock();  // 开锁出去
        }

    }


    public void p2(){
        lock.lock();   //上锁

        try {
//判断
            while(number != 1){
                c2.await();  //等待
            }
//干活
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName());
            }
//通知
            number = 2;
            c3.signal();  //只唤醒c3
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }


    }
    public void p3(){
        lock.lock();   //上锁

        try {
//判断
            while(number != 2){
                c3.await();  //等待
            }
//干活
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName());
            }
//通知
            number = 0;
            c1.signal();  //只唤醒c1
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }


    }
}

 /**
 *
 *  * 多线程之间按顺序调用，实现A->B->C
 *  * 三个线程启动，要求如下：
 *  *
 *  * AA打印5次，BB打印10次，CC打印15次
 *  * 接着
 *  * AA打印5次，BB打印10次，CC打印15次
 *  * ......来10轮
 * 1、有顺序通知，需要有标识位
 *
 * 2、有一个锁Lock，3把钥匙Condition
 *
 * 3、判断标志位
 *
 * 4、输出线程名+第几次+第几轮
 *
 * 5、修改标志位，通知下一个
 * @author shkstart
 * @create 2021-03-06 14:08
 */


public class ThreadOrderAccess {

    public static void main(String[] args) {

        ShareResource shareResource = new ShareResource();
        new Thread(() ->{

            for (int i = 0; i < 3; i++) {
                shareResource.p1();
            }

        },"aaaaaaaaaaa").start();

        new Thread(() ->{

            for (int i = 0; i < 3; i++) {
                shareResource.p2();
            }

        },"bbbbbbbbbbbb").start();
        new Thread(() ->{

            for (int i = 0; i < 3; i++) {
                shareResource.p3();
            }

        },"cccccccccc").start();
    }
}
